package com.itzxx.huazhun.ui.record.uploaded

import android.text.TextUtils
import com.itzxx.huazhun.data.model.RecordChildBean
import com.itzxx.huazhun.data.model.SceneTypeBean
import com.itzxx.huazhun.data.repository.HttpRequestCoroutine
import com.itzxx.huazhun.ui.record.valuation.RecordValuationActivity
import com.itzxx.library_base_ktx.base.viewmodel.BaseViewModel
import com.itzxx.library_base_ktx.callback.livedata.event.EventLiveData
import com.itzxx.library_base_ktx.ext.request
import com.itzxx.library_base_ktx.state.ListDataUiState

class RecordUploadedViewModel : BaseViewModel() {
    //列表数据刷新
    val listDataUiStateLiveData = EventLiveData<ListDataUiState<RecordChildBean>>()

    //类型
    val sceneTypeLiveData = EventLiveData<ArrayList<SceneTypeBean>>()

    //默认第1个
    var currentCheckSceneType = 0

    private var cursor: String = ""


    /**
     * 获取数据列表
     */
    fun getList(isRefresh: Boolean) {
        if (isRefresh) {
            cursor = ""
        }
        request({
            HttpRequestCoroutine.probeCollectionPage(
                "",
                cursor
            )
        }, {
            val listDataUiState =
                ListDataUiState(
                    isSuccess = true,
                    isRefresh = isRefresh,
                    isEmpty = it.list.isEmpty(),
                    hasMore = !it.isLast,
                    isFirstEmpty = TextUtils.isEmpty(cursor) && it.list.isEmpty(),
                    listData = it.list
                )
            cursor = it.cursor
            listDataUiStateLiveData.postValue(listDataUiState)
        }, {
            toast(it.errorMsg)
        })
    }

    /**
     * 获取场景类型
     */
    fun querySceneType() {
        request({
            HttpRequestCoroutine.querySceneType()
        }, {
            sceneTypeLiveData.postValue(it)
        }, {
        })
    }

    fun onEvaluateEvent(list: List<RecordChildBean>) {
        val tempList = arrayListOf<Int>()
        val equipmentIdList = arrayListOf<String>()
        list.forEach {
            if (it.isCheck) {
                tempList.add(it.id)
                if (!TextUtils.isEmpty(it.equipmentId))
                    equipmentIdList.add(it.equipmentId)
            }
        }
        if (tempList.isEmpty()) {
            toast("请选择采集记录")
            return
        }

        baseContext.value?.let { that->
            val equipmentId =
                if (equipmentIdList.isNotEmpty() && equipmentIdList.all { it == equipmentIdList.first() }) {
                    equipmentIdList[0]
                } else {
                    ""
                }
            RecordValuationActivity.startActivity(
                that,
                sceneTypeLiveData.value!![currentCheckSceneType].value,
                tempList,
                equipmentId
            )
        }
    }
}